package midi;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.sound.midi.Track;


public class MidiPhrase implements Trackable{
	private List<MidiNote> midiNotes;
	
	public MidiPhrase(){
		initMidiNotes();
	}
	
	public MidiPhrase(List<MidiNote> midiNotes){
		this.midiNotes = midiNotes;
	}
	
	public MidiPhrase(MidiNote[] midiNotes){
		initMidiNotes();
		for (int i = 0; i < midiNotes.length; i++){
			this.midiNotes.add(midiNotes[i]);
		}
	}
	
	public MidiPhrase(int noteNumbers[], int velocities[], long lengths[]){
		initMidiNotes();
		
		for (int i = 0; i < noteNumbers.length; i++){
			midiNotes.add(new MidiNote(noteNumbers[i], velocities[i], lengths[i]));
		}
	}
	
	private void initMidiNotes(){
		this.midiNotes = new LinkedList<MidiNote>();
	}
	
	public void addNote(MidiNote note){
		midiNotes.add(note);
	}
	
	public void addNote(int index, MidiNote note){
		midiNotes.add(index, note);
	}
	
	public void addNotes(MidiNote[] notes){
		for(int i = 0; i < notes.length; i++){
			midiNotes.add(notes[i]);
		}
	}
	
	public void addNotes(int index, MidiNote[] notes){
		for (int i = 0; i < notes.length; i++){
			addNote(index + i, notes[i]);
		}
	}
	
	public boolean addNotes(Collection<MidiNote> notes){
		return midiNotes.addAll(notes);
	}
	
	public boolean addNotes(int index, Collection<MidiNote> notes){
		return midiNotes.addAll(index, notes);
	}
	
	public MidiNote getNote(int index){
		return midiNotes.get(index);
	}
	
	public void removeNote(int index){
		midiNotes.remove(index);
	}
	
	public boolean removeNote(MidiNote note){
		return midiNotes.remove(note);
	}
	
	public boolean removeAll(Collection<MidiNote> notes){
		return midiNotes.removeAll(notes);
	}
	
	public List<MidiNote> getMidiNotes(){
		return midiNotes;
	}
	
	public void setMidiNotes(List<MidiNote> notes){
		this.midiNotes = notes;
	}
	
	public void setMidiNotes(MidiNote[] notes){
		initMidiNotes();
		addNotes(notes);
	}
	

	
	public void addToTrack(Track track, int channel, long prevTicks){
		Iterator<MidiNote> iter = midiNotes.iterator();
		MidiNote curr;
		
		
		while(iter.hasNext()){
			curr = iter.next();
			
			curr.addToTrack(track, channel, prevTicks);
			prevTicks += curr.getLength();
		}
	}
	
	
	
}
